package thread;

/**
 *
 *
 *
 *
 *
 * @author Luka
 * @date 2021/06/04 17:35
 **/
public class DeadLockDemo2 {
    //定义两个锁对象，"筷子"和"勺"
    public static Object chopsticks = new Object();
    public static Object spoon = new Object();

    public static void main(String[] args) {
        Thread np = new Thread() {
            public void run() {
                System.out.println("北方人开始吃饭.");
                System.out.println("北方人去拿筷子...");
                synchronized (chopsticks) {
                    System.out.println("北方人拿起了筷子开始吃饭...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                    System.out.println("北方人吃完了饭");
                }
                System.out.println("北方人放下了筷子");
                System.out.println("北方人去拿勺子...");
                synchronized (spoon) {
                    System.out.println("北方人拿起了勺子开始喝汤...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                    System.out.println("北方人喝完了汤");
                }
                System.out.println("北方人放下了勺");
                System.out.println("北方人放下了筷子，吃饭完毕!");
            }
        };


        Thread sp = new Thread() {
            public void run() {
                System.out.println("南方人开始吃饭.");
                System.out.println("南方人去拿勺...");
                synchronized (spoon) {
                    System.out.println("南方人拿起了勺开始喝汤...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                    System.out.println("南方人喝完了汤");
                }
                System.out.println("南方人放下了勺子");
                System.out.println("南方人去拿筷子...");
                synchronized (chopsticks) {
                    System.out.println("南方人拿起了筷子开始吃饭...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                    System.out.println("南方人吃完了饭");
                }
                System.out.println("南方人放下了筷子");
                System.out.println("南方人放下了筷子，吃饭完毕!");
            }


        };

        np.start();
        sp.start();


    }
}